package com.xu.cloud.common.util;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 获取HttpServlet工具类
 *
 * @author xuguan
 * @since 2024/1/27
 */
public class HttpServletUtil {

    public static HttpServletRequest currentRequest() {
        return currentRequestAttributes().getRequest();
    }

    public static HttpServletResponse currentResponse() {
        return currentRequestAttributes().getResponse();
    }

    public static ServletRequestAttributes currentRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    }

    public static void downLoad(String fileName, byte[] data) {
        final HttpServletResponse response = currentResponse();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        try {
            final ServletOutputStream sos = response.getOutputStream();
            StreamUtils.copy(data, sos);
            sos.flush();
        } catch (IOException e) {
            throw new RuntimeException("下载文件字节数组拷贝到响应流失败", e);
        }
    }

    public static void temporaryRedirect(String redirectUrl) {
        final HttpServletResponse response = currentResponse();
        response.setStatus(HttpStatus.TEMPORARY_REDIRECT.value());
        response.setHeader("Location", redirectUrl);
    }

    public static Map<String, String> getRequestHeaders() {
        final HttpServletRequest request = currentRequest();
        final Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            final String headerName = headerNames.nextElement();
            headers.put(headerName, request.getHeader(headerName));
        }
        return headers;
    }

    public static Map<String, String> getResponseHeaders() {
        final HttpServletResponse response = currentResponse();
        final Collection<String> headerNames = response.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        for (String headerName : headerNames) {
            headers.put(headerName, response.getHeader(headerName));
        }
        return headers;
    }

    public static Map<String, String> getRequestParams() {
        final HttpServletRequest request = currentRequest();
        final Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        Map<String, String> requestParams = new HashMap<>();
        for (Map.Entry<String, String[]> entry : entrySet) {
            requestParams.put(entry.getKey(), String.join(",", entry.getValue()));
        }
        return requestParams;
    }

    public static boolean isJsonRequest() {
        final HttpServletRequest request = currentRequest();
        final String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);
        return StringUtils.hasText(contentType) &&
                contentType.toLowerCase().startsWith(MediaType.APPLICATION_JSON_VALUE);
    }

    public static boolean isJsonResponse() {
        final HttpServletResponse response = currentResponse();
        final String contentType = response.getHeader(HttpHeaders.CONTENT_TYPE);
        return StringUtils.hasText(contentType) &&
                contentType.toLowerCase().startsWith(MediaType.APPLICATION_JSON_VALUE);
    }
}
